package com.fourgirls.xiaoxiang.controller;

import com.fourgirls.xiaoxiang.exception.Result;
import com.fourgirls.xiaoxiang.pojo.Medicine.MedicineIdVo;
import com.fourgirls.xiaoxiang.pojo.Medicine.MedicineNumberVo;
import com.fourgirls.xiaoxiang.pojo.Medicine.MedicineVo;
import com.fourgirls.xiaoxiang.pojo.Shopping.ShoppingVo;
import com.fourgirls.xiaoxiang.pojo.Shopping.UserNameShoppingVo;
import com.fourgirls.xiaoxiang.service.Medicine.MedicineService;
import com.fourgirls.xiaoxiang.service.Shopping.UserShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class ShoppingController {

    @Autowired
    UserShoppingService userShoppingService;

    @Autowired
    MedicineService medicineService;


    //---------------------------------------------------------------查询分割线--------------------------------------------------------

    /**
     * 查询address表中的所有数据(一对多的级联，查询user表中用户对应的收货地址)
     *
     * @return 查询的数据
     */
    @RequestMapping("findAllUserShopping")
    public Result findAllUserShopping(@RequestBody UserNameShoppingVo userNameShoppingVo) {
        return Result.ok().put("data", userShoppingService.findAllUserShopping(userNameShoppingVo));
    }

    //---------------------------------------------------------------增加分割线--------------------------------------------------------

    /**
     * 往shopping表中的增加一条数据
     *
     * @return 查询的数据
     */
    @RequestMapping("addShopping")
    public Result addShopping(@RequestBody ShoppingVo shoppingVo) {

        int result = userShoppingService.addShopping(shoppingVo);

        MedicineIdVo medicineIdVo = new MedicineIdVo();
        medicineIdVo.setMedicineId(shoppingVo.getMedicineId());
        MedicineVo medicineVo = medicineService.findAllMedicineId(medicineIdVo);
        System.out.println(medicineVo.getMedicineNumber());

        MedicineNumberVo medicineNumberVo = new MedicineNumberVo();
        //得到shopping表中的Id和shopping表中的Id
        medicineNumberVo.setMedicineId(shoppingVo.getMedicineId());
        medicineNumberVo.setMedicineNumber(medicineVo.getMedicineNumber()-shoppingVo.getShoppingMedicineNumber());
        //同时修改medicine的数量
        medicineService.updateMedicineNumber(medicineNumberVo);

        return Result.ok().put("data",result);
    }
}
